<template>
  <div id="box">
    <div id="search">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="角色名">
          <el-input v-model="searchForm.searchParams.roleCh" placeholder="请输入角色名"></el-input>
        </el-form-item>
        <el-form-item label="权限标识">
          <el-input v-model="searchForm.searchParams.roleEn" placeholder="请输入权限字符"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="onSearchSubmit">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div id="header-bth">
      <el-button type="primary" size="small" icon=el-icon-circle-plus-outline @click="showAddRole">新增</el-button>
    </div>
    <div id="role-table">
      <el-table
          :data="tableData"
          stripe
          height="310"
          style="width:100%">
        <el-table-column label="角色名" prop="roleCh">
        </el-table-column>

        <el-table-column label="权限标识" prop="roleEn">
        </el-table-column>

        <el-table-column label="描述" prop="comments">
        </el-table-column>

        <el-table-column label="创建时间" width="200px" prop="createTime">
        </el-table-column>

        <el-table-column label="操作" width="280px">
          <template slot-scope="scope">
            <el-button
                icon="el-icon-edit"
                size="mini"
                @click="handleEdit(scope.$index, scope.row)">
            </el-button>

            <el-popconfirm title="确定删除吗？" @confirm="deleteRole(scope.$index, scope.row)">
              <el-button
                  slot="reference"
                  size="mini"
                  type="danger"
                  icon="el-icon-delete">
              </el-button>
            </el-popconfirm>
            <el-button
                size="mini"
                type="success"
                @click="handleAuth(scope.$index, scope.row)">分配权限
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div id="nav-page">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="pageSizes"
          :page-size="searchForm.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>
    <!--添加 编辑角色信息弹窗-->
    <el-dialog :title="dialogTitle" :visible.sync="addRoleFormVisible" width="50%" @close="clearInfo">
      <el-form :model="roleForm" ref="roleInfo" :rules="roleRules" label-width="90px" size="medium">
        <el-input v-model="roleForm.roleId" autocomplete="off" v-show="false"></el-input>
        <el-form-item label="角色名" prop="roleCh">
          <el-input v-model="roleForm.roleCh" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="权限字符" prop="roleEn">
          <el-input v-model="roleForm.roleEn" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="comments">
          <el-input v-model="roleForm.comments" show-word-limit maxlength="100" type="textarea"
                    :autosize="{ minRows: 5, maxRows: 10 }" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveOrUpdate">确 定</el-button>
      </div>
    </el-dialog>

    <!--分配权限-->
    <el-dialog title="分配权限" :visible.sync="authTreeVisible" width="30%" @close="clearTree">
      <el-tree
          ref="tree"
          :data="treeData"
          show-checkbox
          accordion
          node-key="id"
          :default-checked-keys="defaultCheckedKeys"
          :default-expand-all="false"
          :props="defaultProps">
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addRolePermissions">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

import {addRoal, deleteRoal, editRoal, editRolePermissions, getRoleById, roleList, rolePage} from "@/api/role";
import {permissionList, treeList} from "@/api/permission";
import {listToTree} from "@/utils/treeUtil";

export default {
  name: "RoleView",
  data() {
    return {
      tableData: [],
      pageSizes: [5, 10, 15],
      total: 10,
      roleId: '',
      addRoleFormVisible: false,
      authTreeVisible: false,
      authTreeCheckedKeys: [],
      defaultCheckedKeys: [],
      dialogTitle: '',
      roleForm: {},
      searchForm: {
        searchParams: {
          roleCh: '',
          roleEn: ''
        },
        limit: 5,
        page: 1
      },
      roleRules: {
        roleCh: [{required: true, message: '请输入角色名', trigger: 'blur'}],
        roleEn: [{required: true, message: '请输入角色标识', trigger: 'blur'}]
      },
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      /*权限树形结构数据*/
      treeData: [
        {
          id:1,
          title:"系统管理",
          children:[
            {
              id:3,
              title:'用户管理',
              children:[
                {
                  id:4,
                  title:'添加用户'
                },
                {
                  id:5,
                  title:'删除用户'
                },
                {
                  id:6,
                  title:'修改用户'
                },
                {
                  id:7,
                  title:'查询用户'
                }
              ]
            }
          ]
        }
      ]
    }
  },
  methods: {
    // 编辑角色
    handleEdit(index, row) {
      this.dialogTitle = "编辑角色"
      this.addRoleFormVisible = true
      this.roleForm=row
      //  发送异步请求 根据角色id查询角色信息 实现数据回显

    },
    // 删除角色
    deleteRole(index, row) {
      // 发送异步请求 根据角色id 删除角色信息
      let rid = row.roleId
      console.log(rid)
      deleteRoal(rid).then(response=>{
        if (response.code===0){
          this.$message.success(response.message)
          this.searchForm.page=1
          this.list()
        }
      })



    },
    saveOrUpdate() {
      this.$refs.roleInfo.validate(valid => {
        if (!valid) {
          this.$message.warning("请输入必要数据")
          return
        }
            if (this.dialogTitle === '添加角色') {
              addRoal(this.roleForm).then(response => {
                if (response.code === 0) {
                  this.$message.success(response.message)
                  this.addRoleFormVisible=false
                }
              })
            }else if (this.dialogTitle === '编辑角色') {
                editRoal(this.roleForm).then(response => {
                  if (response.code === 0) {
                    this.$message.success(response.message)
                    this.addRoleFormVisible=false
                  }
                })
            }
        //  发送异步请求   实现角色的添加或修改    roleId

      })

    },
    /*分配权限*/
    async handleAuth(index, row) {
      // 显示权限分配弹出层
      this.authTreeVisible = true
      this.roleId = row.roleId
      // 发送异步请求 渲染 权限树形结构  {code,message,data:{}}
      let response=await treeList()
      this.treeData=listToTree(response.data.permissionList)
      // 根据角色id  回显当前角色的权限  isMenu = 2
     let response1= await getRoleById(this.roleId)
      this.defaultCheckedKeys=response1.data.defaultKeys


    },
    addRolePermissions() {
       let HalfCheckedKeys = this.$refs.tree.getHalfCheckedKeys()  // [1,2,3]   半选
       let CheckedKeys = this.$refs.tree.getCheckedKeys()  //  [4,5,6]         全选
       let newKeys = [...HalfCheckedKeys,...CheckedKeys]   // [1,2,3,4,5,6]  <=  [...HalfCheckedKeys,...CheckedKeys]
        let rid=this.roleId
      let rolePermissions={
         newKeys,rid
      }
      editRolePermissions(rolePermissions).then(response=>{
        if (response.code === 0) {
          this.$message.success(response.message)
          this.authTreeVisible=false
          location.reload()
        }
      })
    },
    //清空权限回显数据
    clearTree() {
      this.defaultCheckedKeys = []
    },
    // 搜索角色
    onSearchSubmit() {
      this.searchForm.page = 1
      this.list(this.searchForm)
    },
    // 改变每页显示的条数触发
    handleSizeChange(val) {
      this.searchForm.limit = val;
      this.list(this.searchForm)
    },
    // 改变页码触发
    handleCurrentChange(val) {
      this.searchForm.page = val;
      this.list(this.searchForm)
    },
    // 显示弹出层
    showAddRole() {
      this.dialogTitle = "添加角色"
      this.addRoleFormVisible = true
    },
    //清空校验规则
    clearInfo() {
      this.roleForm = {}
      this.$refs.roleInfo.clearValidate()
    },



    // 加载角色列表
    list() {

        rolePage(this.searchForm).then(res => {
          if (res.code === 0) {
            this.tableData=res.data.tableData
            this.total = res.data.total
          }
        })
      }


  },
  created() {
    // 查询角色列表
       this.list()
  }
}
</script>

<style scoped>

#box {
  width: 95%;
  margin: 5px auto 0;
}

#search {
  width: 100%;
  height: 50px;
  padding-bottom: 20px;
  margin-top: 10px;
  margin-bottom: 20px;
  border-bottom: 1px solid #eee;
}

#header-bth {
  margin-bottom: 25px;
}

.el-button {
  margin-left: 5px;
  margin-right: 5px;
}

#nav-page {
  margin-top: 15px;
  margin-bottom: 30px;
}
</style>